package com.maimao.user.controller.sys;

import com.maimao.api.sys.ResourcesApi;
import com.maimao.core.constant.Constants;
import com.maimao.core.enums.RespCode;
import com.maimao.core.model.auth.AuthUser;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.DateUtils;
import com.maimao.core.utils.Oauth2Util;
import com.maimao.model.user.sys.Resources;
import com.maimao.user.controller.base.BaseController;
import com.maimao.user.service.sys.ResourceService;
import com.maimao.model.user.sys.dto.DelDto;
import com.maimao.model.user.sys.dto.ResourceSearch;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2020/12/2 4:28 下午
 */
@RestController
public class ResourcesController extends BaseController implements ResourcesApi {
    @Autowired
    private ResourceService resourceService;

    /**
     * 获取登录用户资源列表
     *
     * @return
     */
    @Override
    public Result<?> getResourceList() {
        AuthUser authUser = checkAndGetAuthUser();
        //TODO 后台用户尽量不调 否则可能因为id太长转换错误
        List<Resources> resources = resourceService.resourceListByUserId(Integer.valueOf(authUser.getId()));
        return Result.okData(RespCode.OK, resources);
    }

    @Override
    public Result<?> treeData(@RequestParam(value = "all",required = false)Integer all) {
        List<Resources> resources = resourceService.treeData(all);
        return Result.okData(RespCode.OK, resources);
    }

    @Override
    public Result<?> searchByNameLike(String key) {
        if (StringUtils.isEmpty(key)) {
            return Result.okData(RespCode.OK, null);
        }
        List<String> keys = resourceService.searchByNameLike(key);
        return Result.okData(RespCode.OK, keys);
    }

    /**
     * 查询parentId的直接子资源
     */
    @Override
    public Result<?> selectChild1(Integer parentId, Integer page, Integer size,ResourceSearch search) {
        if (parentId == null || parentId < 0) {
            return Result.okData(RespCode.OK, null);
        }
        return Result.okData(RespCode.OK, resourceService.selectChild1(parentId, page, size,search));
    }

    @Override
    public Result<?> add(@Valid Resources resources, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return dtoInValid(bindingResult);
        }
        Result<Void> result = checkInput(resources);
        if (result != null) {
            return result;
        }
        AuthUser authUser = Oauth2Util.getUserFromRequest(getRequest());
        resources.setCreateUser(Integer.valueOf(authUser.getId()));
        resources.setCreateTime(DateUtils.now());
        resources.setUpdateTime(DateUtils.now());
        resources.setUpdateUser(Integer.valueOf(authUser.getId()));
        return resourceService.add(resources);
    }

    @Override
    public Result<?> update(@Valid Resources resources, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return dtoInValid(bindingResult);
        }
        if(resources.getId()==null || resources.getId()<0){
            return Result.notValid();
        }
        Result<Void> result = checkInput(resources);
        if (result != null) {
            return result;
        }
        AuthUser authUser = Oauth2Util.getUserFromRequest(getRequest());
        resources.setUpdateTime(DateUtils.now());
        resources.setUpdateUser(Integer.valueOf(authUser.getId()));
        return resourceService.update(resources);

    }


    @Override
    public Result<?> updateStatusBatch(@Valid @RequestBody DelDto delDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return dtoInValid(bindingResult);
        }
        for (Integer id : delDto.getIds()) {
            if (id==null || id<0){
                return Result.notValid();
            }
        }

        resourceService.updateStatusBatch(delDto);

        return Result.ok(RespCode.OK,"ok");
    }

    private Result dtoInValid(BindingResult bindingResult) {
        return Result.fail(RespCode.NOT_VALID, bindingResult.getFieldErrors().get(0).getDefaultMessage());
    }

    private Result<Void> checkInput(Resources resources) {
        if (resources.getStatus() == null || resources.getStatus() < 0) {
            resources.setStatus(1);
        }
        switch (resources.getType()) {
            case Constants.LEFT_NAV:
            case Constants.BUTTON:
                //左侧导航菜单
                resources.setPath(Constants.EMPTY);
                resources.setComponent(Constants.EMPTY);
                resources.setRedirect(Constants.EMPTY);
                if (resources.getType().equals(Constants.BUTTON)) {
                    resources.setSide(false);
                } else {
                    resources.setSide(true);
                }
                break;
            case Constants.MENU:
                if (StringUtils.isAnyEmpty(resources.getComponent(), resources.getPath())) {
                    return Result.notValid("请填写菜单路径和资源路径");
                }
                if (resources.getSide() == null) {
                    return Result.notValid("请选择是左侧菜单还是顶部菜单");
                }
                break;
            case Constants.READ_WRITE:
                resources.setPath(Constants.EMPTY);
                resources.setComponent(Constants.EMPTY);
                resources.setRedirect(Constants.EMPTY);
                resources.setSide(false);
                String name = resources.getName();
                if (!Constants.READ_WRITE_LIST.contains(name)) {
                    return Result.notValid("读写类型不正确");
                }
                break;
            default:
                break;
        }
        return null;
    }


}
